package com.ruoyi.quality.service.impl;

import java.util.*;
import java.util.stream.Stream;

import cn.hutool.core.bean.BeanUtil;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.quality.domain.TQualityFileItem;
import com.ruoyi.quality.domain.dto.TQualityBizEnterCheckDTO;
import com.ruoyi.quality.domain.dto.TQualityEnterCheckDTO;
import com.ruoyi.quality.service.ITQualityEnterCheckService;
import com.ruoyi.quality.service.ITQualityFileItemService;
import com.ruoyi.quality.service.ITQualityFileService;
import com.ruoyi.safe.domain.BizEnterCheck;
import com.ruoyi.safe.domain.BizEnterCheckProject;
import com.ruoyi.safe.domain.BizEnterTask;
import com.ruoyi.safe.domain.BizProjectCheckRecord;
import com.ruoyi.safe.domain.dto.BizEnterCheckDTO;
import com.ruoyi.safe.domain.dto.EnterCheckDTO;
import com.ruoyi.safe.domain.dto.EntityIdAppDTO;
import com.ruoyi.safe.domain.dto.ProjectSearchDTO;
import com.ruoyi.safe.domain.vo.BizEnterCheckProjectVO;
import com.ruoyi.safe.domain.vo.CommonProjectVO;
import com.ruoyi.safe.mapper.BizEnterCheckProjectMapper;
import com.ruoyi.safe.mapper.BizEnterTaskMapper;
import com.ruoyi.safe.mapper.BizProjectCheckRecordMapper;
import com.ruoyi.safe.mapper.CommonProjectMapper;
import com.ruoyi.safe.service.*;
import com.ruoyi.safe.service.impl.BizEnterCheckProjectServiceImpl;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.ISysUserService;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

/**
 * 公司检查明细Service业务层处理
 * 
 * @author mahl2
 * @date 2024-02-26
 */
@Service
public class TQualityEnterCheckServiceImpl implements ITQualityEnterCheckService
{
    @Value("${minio.bucketName}")
    private String bucketName;
    @Autowired
    IBizEnterCheckService bizEnterCheckService;

    @Autowired
    private BizEnterCheckProjectMapper bizEnterCheckProjectMapper;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private CommonProjectMapper commonProjectMapper;
    @Autowired
    private BizEnterTaskMapper bizEnterTaskMapper;
    @Autowired
    private BizProjectCheckRecordMapper bizProjectCheckRecordMapper;
    @Autowired
    private ITQualityFileService iTQualityFileService;
    @Autowired
    ISysUserService sysUserService;
    @Autowired
    private IBizEnterTaskService bizEnterTaskService;

    /**
     * 查询公司检查-项目列表
     * @param tQualityEnterCheckDTO
     * @return
     */
    @Override
    public List<BizEnterCheckProjectVO> selectBizEnterCheckProjectList(TQualityEnterCheckDTO tQualityEnterCheckDTO, SysUser user)
    {
        BizEnterCheckProject bizEnterCheckProject = new BizEnterCheckProject();

        BeanUtil.copyProperties(tQualityEnterCheckDTO, bizEnterCheckProject);
        bizEnterCheckProject.setId(tQualityEnterCheckDTO.getId());
        bizEnterCheckProject.setBizEnterCheckId(tQualityEnterCheckDTO.getBizEnterCheckId());
        bizEnterCheckProject.setGroupName(tQualityEnterCheckDTO.getGroupName());
        bizEnterCheckProject.setGroupLeader(tQualityEnterCheckDTO.getGroupLeader());
        bizEnterCheckProject.setGroupMember(tQualityEnterCheckDTO.getGroupMember());
        bizEnterCheckProject.setPlanEndTime(tQualityEnterCheckDTO.getPlanEndTime());
        bizEnterCheckProject.setPlanStartTime(tQualityEnterCheckDTO.getPlanStartTime());

        List<BizEnterCheckProject> list
                = bizEnterCheckProjectMapper.selectBizEnterCheckProjectList(bizEnterCheckProject);
        setListParamNames(list);

        List<BizEnterCheckProjectVO> voList = new ArrayList<>();
        list.forEach(item -> {
            BizEnterCheckProjectVO vo = getBizEnterCheckProjectVO(user, item);
            voList.add(vo);
        });

        return voList;
    }

    /**
     * 拆分质量问题文件
     *
     * @param listFileItems 质量问题拆分文件
     * @return 结果
     */
    public int splitFile(List<TQualityFileItem> listFileItems)
    {
        if (listFileItems.size() > 0)
        {
            TQualityFileItem item = listFileItems.get(0);
            EntityIdAppDTO entityIdAppDTO = new EntityIdAppDTO();
            entityIdAppDTO.setId(item.getFileId());
            LoginUser loginUser = SecurityUtils.getLoginUser();
            entityIdAppDTO.setUserName(loginUser.getUser().getUserName());
            Integer nSize = updateProjectStatusTwo(entityIdAppDTO);
            for (TQualityFileItem item0 : listFileItems)
            {
                item0.setCheckPeopleId(loginUser.getUserId().toString());
            }
            return iTQualityFileService.splitFile(listFileItems,String.valueOf(item.getFileId()));
        }
        else
        {
            return 0;
        }
    }

    private void setListParamNames(List<BizEnterCheckProject> bizEnterCheckProjectList) {
        bizEnterCheckProjectList.forEach(item -> {
            //赋值参检人员
            List<String> memberList = new ArrayList<>();
            String str1 = item.getGroupMember();
            if (str1 == null || str1.isEmpty())
            {
                item.setGroupMemberList(memberList);
            }
            else
            {
                Arrays.stream(item.getGroupMember().split(",")).forEach(a -> {
                    memberList.add(sysUserMapper.selectUserById(Long.valueOf(a)).getNickName());
                    item.setGroupMemberList(memberList);
                });
            }

            //赋值参见组长
            List<String> leaderList = new ArrayList<>();
            String str2 = item.getGroupLeader();
            if (str2 == null || str2.isEmpty())
            {
                item.setGroupLeaderList(leaderList);
            }
            else
            {
                Arrays.stream(item.getGroupLeader().split(",")).forEach(o -> {
                    leaderList.add(sysUserMapper.selectUserById(Long.valueOf(o)).getNickName());
                    item.setGroupLeaderList(leaderList);
                });
            }

            //赋值检查项目
            List<String> projectIdList = new ArrayList<>();
            String str3 = item.getCheckProjectIds();
            if (str3 == null || str3.isEmpty())
            {
                item.setCheckProjectIdsList(projectIdList);
            }
            else
            {
                Arrays.stream(item.getCheckProjectIds().split(",")).forEach(p -> {
                    projectIdList.add(commonProjectMapper.selectCommonProjectById(Long.valueOf(p)).getName());
                    item.setCheckProjectIdsList(projectIdList);
                });
            }
        });
    }

    @NotNull
    private BizEnterCheckProjectVO getBizEnterCheckProjectVO(SysUser user, BizEnterCheckProject item) {
        BizEnterCheckProjectVO vo = new BizEnterCheckProjectVO();
        BeanUtil.copyProperties(item, vo);
        BizEnterTask task = new BizEnterTask();
        task.setBizEnterCheckProjectId(item.getId());
        List<BizEnterTask> taskList = bizEnterTaskMapper.selectBizEnterTaskList(task);
        if (taskList.size() > 0)
        {
            BizEnterTask dbData = taskList.get(0);

            List<BizProjectCheckRecord> records = bizProjectCheckRecordMapper
                    .selectListByProjectCheckId(dbData.getBizEnterCheckProjectId());
            dbData.setHiddenNumber(
                    Math.toIntExact(records.stream().filter(r -> Stream.of("1", "2", "3")
                            .anyMatch(s -> s.equals(r.getHiddenDangerStatus()))).count()));
            vo.setBizEnterTask(dbData);
        }
        else
        {
            vo.setBizEnterTask(null);
        }
        vo.setHasAddRecordPermission(item.getGroupLeader().contains(String.valueOf(user.getUserId()))
                || item.getGroupMember().contains(String.valueOf(user.getUserId())));
        List<CommonProjectVO> projectVOS = commonProjectMapper.selectCommonProjectList(new ProjectSearchDTO());
        projectVOS.forEach(p -> {
            if (p.getName().equals(item.getCheckProjectIdsList().get(0))) {
                vo.setDeptName(p.getDeptName());
            }
        });
        return vo;
    }

    /**
     * 公司检查--我参与的检查
     * @param bizEnterCheckDTO
     * @return
     */
    public List<BizEnterCheck> myList(BizEnterCheckDTO bizEnterCheckDTO)
    {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        if (bizEnterCheckDTO.getPageNum() != null && bizEnterCheckDTO.getPageSize() != null) {
            PageUtils.startPage(bizEnterCheckDTO.getPageNum(), bizEnterCheckDTO.getPageSize());
        }
        BizEnterCheck bizEnterCheck = new BizEnterCheck();
        BeanUtils.copyProperties(bizEnterCheckDTO, bizEnterCheck);
        List<BizEnterCheck> list = bizEnterCheckService.selectBizEnterMyList(bizEnterCheck, user);
        return list;
    }

    /**
     * 公司检查--我的待办
     * @param bizEnterCheckDTO
     * @return
     */
    public List<EnterCheckDTO> myTodo(BizEnterCheckDTO bizEnterCheckDTO)
    {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        if (bizEnterCheckDTO.getPageNum() != null && bizEnterCheckDTO.getPageSize() != null) {
            PageUtils.startPage(bizEnterCheckDTO.getPageNum(), bizEnterCheckDTO.getPageSize());
        }
        List<EnterCheckDTO> list = bizEnterCheckService.selectToDoList(bizEnterCheckDTO, user);
        return list;
    }

    /**
     * 修改项目自检状态为已结束
     * @param entityIdAppDTO
     * @return
     */
    public Integer updateProjectStatus(EntityIdAppDTO entityIdAppDTO){
        SysUser user = SecurityUtils.getLoginUser().getUser();
        BizEnterTask task = new BizEnterTask();
        task.setBizEnterCheckProjectId(entityIdAppDTO.getId());
        List<BizEnterTask> taskList = bizEnterTaskService.selectBizEnterTaskList(task);
        if (taskList.size() > 0)
        {
            LoginUser loginUser = SecurityUtils.getLoginUser();
            BizEnterTask dbTask = taskList.get(0);
            dbTask.setStatus("3");
            dbTask.setFinishTime(DateUtils.getNowDate());
            dbTask.setUpdateTime(DateUtils.getNowDate());
            dbTask.setUpdateBy(loginUser.getUsername());
            bizEnterTaskService.updateBizEnterTask(dbTask, user);

            // 如果公司检查下面的所有任务都完成了，设置公司检查状态为结束
            List<BizEnterTask> allTasks = bizEnterTaskService.selectTaskListByCheckId(dbTask.getBizEnterCheckId());
            BizEnterCheck enterCheck = bizEnterCheckService.selectBizEnterCheckById(dbTask.getBizEnterCheckId());
            if (allTasks.stream().allMatch(t -> "3".equals(t.getStatus()))) {
                enterCheck.setCheckStatus("3");
            } else {
                enterCheck.setCheckStatus("2");
            }
            enterCheck.setUpdateTime(DateUtils.getNowDate());
            enterCheck.setUpdateBy(loginUser.getUsername());
            bizEnterCheckService.updateBizEnterCheck(enterCheck, user);
            return 0;
        }
        return -1;
    }

    /**
     * 修改项目自检状态为已结束
     * @param entityIdAppDTO
     * @return
     */
    public Integer updateProjectStatusTwo(EntityIdAppDTO entityIdAppDTO){
        SysUser user = SecurityUtils.getLoginUser().getUser();
        BizEnterTask task = new BizEnterTask();
        task.setBizEnterCheckProjectId(entityIdAppDTO.getId());
        List<BizEnterTask> taskList = bizEnterTaskService.selectBizEnterTaskList(task);
        if (taskList.size() > 0)
        {
            LoginUser loginUser = SecurityUtils.getLoginUser();
            BizEnterTask dbTask = taskList.get(0);
            dbTask.setStatus("2");
            dbTask.setFinishTime(DateUtils.getNowDate());
            dbTask.setUpdateTime(DateUtils.getNowDate());
            dbTask.setUpdateBy(loginUser.getUsername());
            bizEnterTaskService.updateBizEnterTask(dbTask, user);

            BizEnterCheck enterCheck = bizEnterCheckService.selectBizEnterCheckById(dbTask.getBizEnterCheckId());
            enterCheck.setCheckStatus("2");
            enterCheck.setUpdateTime(DateUtils.getNowDate());
            enterCheck.setUpdateBy(loginUser.getUsername());
            bizEnterCheckService.updateBizEnterCheck(enterCheck, user);
            return 0;
        }
        return -1;
    }

    @Override
    public Integer splitFileNew(List<TQualityFileItem> listFileItems) {
        if (listFileItems.size() > 0)
        {
            TQualityFileItem item = listFileItems.get(0);
            EntityIdAppDTO entityIdAppDTO = new EntityIdAppDTO();
            entityIdAppDTO.setId(item.getFileId());
            LoginUser loginUser = SecurityUtils.getLoginUser();
            entityIdAppDTO.setUserName(loginUser.getUser().getUserName());
            Integer nSize = updateProjectStatusTwo(entityIdAppDTO);
            for (TQualityFileItem item0 : listFileItems)
            {
                item0.setCheckPeopleId(loginUser.getUserId().toString());
            }
            return iTQualityFileService.splitFileNew(listFileItems,String.valueOf(item.getFileId()));
        }
        else
        {
            return 0;
        }
    }
}
